import {defineStore} from 'pinia'
import { ref } from 'vue'
import { TypeApiSettingI } from '~@/api/apiTypes';
import { apiGetSettings } from '~@/api/settings';
import { pinia } from '../storeIndex';
import { setSiteTitle } from '~@/untils/titleController';

export const useSettingsStore=defineStore('settings',()=>{
    const loadingRef=ref(true);
    const dataRef=ref<TypeApiSettingI>();

    const fetchSetting=async ()=>{
        loadingRef.value=true;
        dataRef.value=await apiGetSettings();
        loadingRef.value=false;

        if(dataRef.value.favicon){
            let link:any=document.querySelector("link[ref='shortcut icon']");
            if(link){
                return;
            }

            link=document.createElement('link');
            link.rel= "shortcut icon";
            link.type = "images/x-icon";
            link.href = dataRef.value.favicon;
            document.querySelector("head")!.appendChild(link);
        }
        if(dataRef.value.siteTitle){
            setSiteTitle(dataRef.value.siteTitle);
        }
    }

    return {
        loadingRef,
        dataRef,
        fetchSetting
    }
});

export function useSettingStoreWithoutSetup(){
    return useSettingsStore(pinia)
}